package com.ds.smartstudio.utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.ds.smartstudio.entity.User;
import com.ds.smartstudio.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
@Component
@Slf4j
public class TokenUtils {

    private static UserService staticUserService;

    @Autowired
    private UserService userService;

    @PostConstruct
    public void setStaticUserService() {
        staticUserService = userService;
    }


    public static  String genToken(String userId, String sign) {
        return JWT.create()
                .withAudience(userId)   // 载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 6))   // 10分钟后token过期
                .sign(Algorithm.HMAC256(sign)); // 以password作为token密钥
    }

    public static User getCurrentUser() {
        User user = null;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if (StrUtil.isNotBlank(token)) {
                String userId = JWT.decode(token).getAudience().get(0);
                user = staticUserService.getById((Integer.valueOf(userId)));
            }
        } catch (JWTDecodeException | NumberFormatException e) {
            log.error(e.toString());
        }
        return user;
    }
}
